from datetime import datetime
import pandas as pd
from meteostat import Point, Daily, Normals

class InternetAPI:
    def __init__(self):
        latitude = 39.92  # 纬度
        longitude = 116.35  # 经度
        start_date = datetime(2024, 6, 1)  # 起始日期
        end_date = datetime(2024, 6, 10)  # 结束日期
        # bbox : [min_lat, max_lat, min_lon, max_lon]
        # data = self.weather([latitude, latitude, longitude, longitude], [start_date, end_date])



    def weather(self, bbox, date):
        # https://dev.meteostat.net/python/
        location = Point((bbox[0]+bbox[2])/2, (bbox[1]+bbox[3])/2, 70)
        data = Normals(location, date[0])
        data = data.fetch()
        data = {
            "temperature_avg": {"name": "平均温度", "unit": "摄氏度", "value": round(data['tavg'].mean(), 1) if 'tavg' in data.columns else 'NaN'},
            "temperature_min": {"name": "最低温度", "unit": "摄氏度", "value": round(data['tmin'].min(), 1) if 'tmin' in data.columns else 'NaN'},
            "temperature_max": {"name": "最高温度", "unit": "摄氏度", "value": round(data['tmax'].max(), 1) if 'tmax' in data.columns else 'NaN'},
            "precipitation": {"name": "降水量", "unit": "毫米", "value": round(data['prcp'].mean(), 2) if 'prcp' in data.columns else 'NaN'},
            "snow": {"name": "降雪量", "unit": "毫米", "value": round(data['snow'].mean(), 2) if 'snow' in data.columns else 0},
            "wind_direction": {"name": "平均风向", "unit": "度", "value": round(data['wdir'].mean(), 2) if 'wdir' in data.columns else 'NaN'},
            "wind_speed_avg": {"name": "平均风速", "unit": "公里 / 小时", "value": round(data['wspd'].mean(), 2) if 'wspd' in data.columns else 'NaN'},
            "wind_speed_max": {"name": "最大风速", "unit": "公里 / 小时", "value": round(data['wpgt'].max(), 2) if 'wpgt' in data.columns else 'NaN'},
            "pressure_avg": {"name": "平均气压", "unit": "百帕", "value": round(data['pres'].max(), 2) if 'pres' in data.columns else 'NaN'},
            "sun_duration": {"name": "日照时间", "unit": "分钟", "value": round(data['tsun'].max(), 2) if 'tsun' in data.columns else 'NaN'}
        }

        return {"weather": data}

    def event(self, bbox, date):
        pass

    def information(self, bbox, date):
        pass

    def get_data(self, bbox, date):
        data = {}
        data.update(self.weather(bbox, date))
        return data

#internet = InternetAPI()
#data = internet.get_data([39.92, 116.35,39.92,116.35], [datetime(2021, 6, 1), datetime(2021, 6, 10)])
#print(data)